#include <bits/stdc++.h>

using namespace std;

class Solution
{
public:
    int longestIncreasingPath(vector<vector<int>> &matrix)
    {
        int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        if (matrix.size() == 0 || matrix[0].size() == 0)
        {
            return 0;
        }
        int n = matrix.size(), m = matrix[0].size();
        auto outdegrees = vector<vector<int>>(n, vector<int>(m));
        for (int i = 0; i < n; ++i)
        {
            for (int j = 0; j < m; ++j)
            {
                for (int k = 0; k < 4; ++k)
                {
                    int newRow = i + dirs[k][0], newColumn = j + dirs[k][1];
                    if (newRow >= 0 && newRow < n && newColumn >= 0 && newColumn < m && matrix[newRow][newColumn] > matrix[i][j])
                    {
                        ++outdegrees[i][j];
                    }
                }
            }
        }
        queue<pair<int, int>> q;
        for (int i = 0; i < n; ++i)
        {
            for (int j = 0; j < m; ++j)
            {
                if (outdegrees[i][j] == 0)
                {
                    q.push({i, j});
                }
            }
        }
        int ans = 0;
        while (!q.empty())
        {
            ++ans;
            int size = q.size();
            for (int i = 0; i < size; ++i)
            {
                auto cell = q.front();
                q.pop();
                int row = cell.first, column = cell.second;
                for (int k = 0; k < 4; ++k)
                {
                    int newRow = row + dirs[k][0], newColumn = column + dirs[k][1];
                    if (newRow >= 0 && newRow < n && newColumn >= 0 && newColumn < m && matrix[newRow][newColumn] < matrix[row][column])
                    {
                        --outdegrees[newRow][newColumn];
                        if (outdegrees[newRow][newColumn] == 0)
                        {
                            q.push({newRow, newColumn});
                        }
                    }
                }
            }
        }
        return ans;
    }
};

int main()
{

    // system("pause");
    return 0;
}
